package edu.wisc.hevea.consumer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.protobuf.ServiceException;
import com.wisc.application.ApplicationPolicy;

import edu.wisc.hevea.broker.BrokerManager;
import edu.wisc.hevea.exception.BrokerUnavailableException;
import edu.wisc.hevea.messaging.Message;
import edu.wisc.hevea.messaging.MessagingServiceClient;

public class Consumer {
	private static final Logger logger = LoggerFactory
			.getLogger(Consumer.class);

	private String hostName;
	private ApplicationPolicy appPolicy;
	private BrokerManager brokerManager;
	private MessagingServiceClient messagingServiceClient;

	public Consumer(String hostName, ApplicationPolicy appPolicy) {
		this.sethostName(hostName);
		this.setAppPolicy(appPolicy);
		messagingServiceClient = MessagingServiceClient
				.getMessagingServiceClient(hostName);
		brokerManager = new BrokerManager(appPolicy, hostName,
				messagingServiceClient);
	}

	public String gethostName() {
		return hostName;
	}

	public void sethostName(String hostName) {
		this.hostName = hostName;
	}

	public ApplicationPolicy getAppPolicy() {
		return appPolicy;
	}

	public void setAppPolicy(ApplicationPolicy appPolicy) {
		this.appPolicy = appPolicy;
	}

	public Message getMessage(String topic) throws BrokerUnavailableException,
			ServiceException {
		String nextBroker = brokerManager.getNextBroker();
		logger.info("Getting message from broker " + nextBroker);
		return messagingServiceClient.getMessage(topic, nextBroker);
	}
}
